﻿using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using TradeDataAPI.Core.CacheManager;
using TradeDataAPI.Core.Common;
using TradeDataAPI.Core.Configuration;
using TradeDataAPI.Core.Extensions;
using TradeDataAPI.Core.Extensions.AutofacManager;
using TradeDataAPI.Entity.DomainModels;

namespace TradeDataAPI.Core.Utilities
{
    public class JwtHelper
    {
        private static WebResponseContent webResponse = new WebResponseContent();
        public static ICacheService CacheContext
        {
            get
            {
                return AutofacContainerModule.GetService<ICacheService>();
            }
        }



        /// <summary>
        /// 生成JWT
        /// </summary>
        /// <param name="serInfo"></param>
        /// <returns></returns>
        public static string IssueJwt(UserInfo userInfo)
        {
            string exp = $"{new DateTimeOffset(DateTime.Now.AddMinutes(ManageUser.UserContext.MenuType == 1 ? 43200 : AppSetting.ExpMinutes)).ToUnixTimeSeconds()}";
            var claims = new List<Claim>
                {
                //new Claim(ClaimTypes.Name,userInfo.UserName ),
                //new Claim(ClaimTypes.Role,userInfo.Role_Id ),
                new Claim(JwtRegisteredClaimNames.Jti,userInfo.User_Id.ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                //JWT过期时间
                //验证是否过期 从User读取过期 时间，再将时间戳转换成日期，如果时间在半个小时内即将过期，通知前台刷新JWT
                //int val= HttpContext.User.Claims.Where(x => x.Type == JwtRegisteredClaimNames.Exp).FirstOrDefault().Value;
                //new DateTime(621355968000000000 + (long)val* (long)10000000, DateTimeKind.Utc).ToLocalTime()
                //默认设置jwt过期时间120分钟
                new Claim (JwtRegisteredClaimNames.Exp,exp),
                new Claim(JwtRegisteredClaimNames.Iss,AppSetting.Secret.Issuer),
                new Claim(JwtRegisteredClaimNames.Aud,AppSetting.Secret.Audience),
               };

            //秘钥16位
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSetting.Secret.JWT));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            JwtSecurityToken securityToken = new JwtSecurityToken(issuer: AppSetting.Secret.Issuer, claims: claims, signingCredentials: creds);
            string jwt = new JwtSecurityTokenHandler().WriteToken(securityToken);
            return jwt;
        }



 


        /// <summary>
        /// 解析
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static WebResponseContent SerializeJwts(string jwtStr)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(jwtStr) || jwtStr== "undefined")
                {
                    return webResponse.Error("无效的令牌");
                }
                if (!IsTokenExpired(jwtStr))
                {
                    var jwtHandler = new JwtSecurityTokenHandler();
                    JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
                    var payload = jwtToken.Payload;//获取第5列的值
                    var fifthClaimValue = payload.ElementAt(3).Value.ToString();
                    var ChName = payload.ElementAt(9).Value.ToString();
                    var EnName = payload.ElementAt(10).Value.ToString();
                    var obj = new TokenInfo()
                    {
                        okta_account = fifthClaimValue,
                        ChName = ChName,
                        EnName = EnName,
                    };
                    CacheContext.Add($"{fifthClaimValue}", JsonConvert.SerializeObject(obj));
                    return webResponse.OK("", fifthClaimValue);
                }
                else
                {
                    return webResponse.Error("令牌已经过期");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                return webResponse.Error("无效的令牌");
            }

        }


        /// <summary>
        /// 解析
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static UserInfo SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
            UserInfo userInfo = new UserInfo
            {
                User_Id = Convert.ToInt32(jwtToken.Id),
                Role_Id = (jwtToken.Payload[ClaimTypes.Role] ?? 0).GetInt(),
                UserName = jwtToken.Payload[ClaimTypes.Name]?.ToString()
            };

            return userInfo;
        }


        /// <summary>
        /// 获取过期时间
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static DateTime GetExp(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);

            DateTime expDate = (jwtToken.Payload[JwtRegisteredClaimNames.Exp] ?? 0).GetInt().GetTimeSpmpToDate();
            return expDate;
        }
        public static bool IsExp(string jwtStr)
        {
            return GetExp(jwtStr) < DateTime.Now;
        }


        /// <summary>
        /// 判断token是否过期
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static bool IsTokenExpired(string token)
        {
            var jwtToken = new JwtSecurityToken(token);
            var expirationDate = jwtToken.ValidTo;

            // 检查当前时间是否在过期时间之后
            return DateTime.UtcNow > expirationDate;
        }

        public static int GetUserId(string jwtStr)
        {
            try
            {
                if (jwtStr.IsNullOrEmpty()) return 0;
                jwtStr = jwtStr.Replace("Bearer ", "");
                return new JwtSecurityTokenHandler().ReadJwtToken(jwtStr).Id.GetInt();
            }
            catch
            {
                return 0;
            }
        }
    }



}
